import { createApp } from 'vue'
import { createPinia } from 'pinia'
import naive from 'naive-ui'
import router from './router'
import App from './App.vue'
import { useFileDataStore } from './stores/fileData'
import { useWorkspaceStore } from './stores/workspace'
import './styles.css'

const app = createApp(App)
const pinia = createPinia()

app.use(pinia)
app.use(naive)
app.use(router)

// 初始化应用数据
async function initializeApp() {
  console.log('=== 开始应用初始化 ===')
  
  try {
    // 先初始化文件数据存储
    console.log('步骤1: 初始化文件数据存储...')
    const fileDataStore = useFileDataStore()
    await fileDataStore.initializeFromStorage()
    console.log('文件数据存储初始化完成')
    
    // 再初始化工作区数据（会从fileData store恢复大文件数据）
    console.log('步骤2: 初始化工作区数据...')
    const workspaceStore = useWorkspaceStore()
    await workspaceStore.initializeWorkspaces()
    console.log('工作区数据初始化完成')
    
    // 验证初始化结果
    console.log('=== 应用初始化完成 ===')
    console.log('工作区数量:', workspaceStore.workspaces.length)
    console.log('当前工作区:', workspaceStore.currentWorkspaceId)
    console.log('文件数据内存使用:', fileDataStore.getMemoryUsage())
    
    // 验证数据恢复情况
    for (const workspace of workspaceStore.workspaces) {
      if (workspace.extractedData) {
        console.log(`✓ 工作区 ${workspace.id} 数据恢复成功，长度: ${workspace.extractedData.length}`)
      } else {
        console.warn(`✗ 工作区 ${workspace.id} 数据恢复失败，没有extractedData`)
      }
    }
    
  } catch (error) {
    console.error('应用初始化失败:', error)
    // 即使初始化失败，也要标记为完成，避免无限等待
    throw error
  }
}

// 全局初始化状态
(window as any).__APP_INIT_COMPLETE__ = false

app.mount('#app')

// 应用挂载后初始化数据
initializeApp().then(() => {
  console.log('=== 应用数据初始化完成 ===')
  ;(window as any).__APP_INIT_COMPLETE__ = true
  
  // 触发自定义事件，通知组件数据已准备好
  window.dispatchEvent(new CustomEvent('app-data-initialized'))
}).catch(error => {
  console.error('应用初始化失败:', error)
  ;(window as any).__APP_INIT_COMPLETE__ = true
})
